package com.kangyi.admin.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.admin.mapper.AdminUserMapper;
import com.kangyi.admin.mapper.EntryManagementMapper;
import com.kangyi.admin.mapper.NursingHomeMapper;
import com.kangyi.admin.mapper.UserMapper;
import com.kangyi.admin.service.EntryManagementService;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.EntryManagementPageQueryDTO;
import com.kangyi.dto.RefuseApplicationDTO;
import com.kangyi.entity.AdminUser;
import com.kangyi.entity.NursingHome;
import com.kangyi.entity.NursingHomeApplication;
import com.kangyi.entity.User;
import com.kangyi.exception.DataNotExistException;
import com.kangyi.exception.PermissionsException;
import com.kangyi.exception.ToExamineException;
import com.kangyi.result.EntryManagementPageResult;
import com.kangyi.vo.AdminUserVO;
import com.kangyi.vo.NursingHomeApplicationDetailVO;
import com.kangyi.vo.NursingHomeApplicationPageQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.Period;
import java.util.List;

/**
 * @author Blank
 * @version 1.0
 */
@Service
@Slf4j
public class EntryManagementServiceImpl implements EntryManagementService {

    @Autowired
    private EntryManagementMapper entryManagementMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private NursingHomeMapper nursingHomeMapper;

    @Autowired
    private UserMapper userMapper;

    //调用后检查当前线程id是否有足够的权限进行后续操作
    public void validateUserPermissions() {
        Integer currentId = BaseContext.getCurrentId();
        AdminUserVO adminUserVO = adminUserMapper.selectById(currentId);
        if (!adminUserVO.getPermissions().equals(1)) {
            throw new PermissionsException(MessageConstant.INSUFFICIENT_PRIVILEGE);
        }
    }

    @Override
    public EntryManagementPageResult pageQuery(EntryManagementPageQueryDTO entryManagementPageQueryDTO) {
        validateUserPermissions();
        PageHelper.startPage(entryManagementPageQueryDTO.getPage(),entryManagementPageQueryDTO.getPageSize());
        Page<NursingHomeApplicationPageQueryVO> page = entryManagementMapper.pageQuery(entryManagementPageQueryDTO);
        long total = page.getTotal();
        List<NursingHomeApplicationPageQueryVO> result = page.getResult();

        int pendingReview = 0;
        int approved = 0;
        int rejected = 0;

        for (NursingHomeApplicationPageQueryVO vo : result) {
            if (vo.getStatus() == 0) {
                pendingReview++;
            } else if (vo.getStatus() == 1) {
                approved++;
            } else if (vo.getStatus() == 2){
                rejected++;
            }
        }

        return new EntryManagementPageResult(total,result,pendingReview,approved,rejected);
    }

    @Override
    public void deleteRegistrationApplication(List<Integer> ids) {
        validateUserPermissions();
        entryManagementMapper.deleteRegistrationApplication(ids);
    }

    @Override
    public NursingHomeApplicationDetailVO detailApplication(Integer id) {
        validateUserPermissions();
        NursingHomeApplicationDetailVO nursingHomeApplicationDetailVO = entryManagementMapper.detailApplication(id);
        if (nursingHomeApplicationDetailVO == null) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }
        return nursingHomeApplicationDetailVO;
    }

    @Override
    public void refuseApplication(RefuseApplicationDTO refuseApplicationDTO) {
        validateUserPermissions();
        NursingHomeApplication nursingHomeApplication = entryManagementMapper.getById(refuseApplicationDTO.getId());
        if (nursingHomeApplication.getStatus().equals(1) || nursingHomeApplication.getStatus().equals(2)) {
            throw new ToExamineException(MessageConstant.DO_NOT_REPEAT_THE_OPERATION);
        }
        NursingHomeApplication build = NursingHomeApplication.builder()
                .id(refuseApplicationDTO.getId())
                .rejectionReason(refuseApplicationDTO.getRejectionReason())
                .status(NursingHomeApplication.REJECTED)
                .build();
        entryManagementMapper.refuseApplication(build);
    }

    @Override
    @Transactional
    public void passApplication(Integer applicationId) {
        validateUserPermissions();
        //查询是否有重复操作
        NursingHomeApplication application = entryManagementMapper.getById(applicationId);
        if (application.getStatus().equals(1)) {
            throw new ToExamineException(MessageConstant.DO_NOT_REPEAT_THE_OPERATION);
        }
        //整合nursingHome数据
        NursingHome nursingHome = NursingHome.builder()
                .name(application.getNursingHomeName())
                .organizationId(application.getOrganizationId())
                .addressDescription(application.getAddressDescription())
                .establishmentTime(application.getEstablishmentTime())
                .status(NursingHome.ENABLED)
                .build();
        //新增NursingHome
        try {
            nursingHomeMapper.addNursingHome(nursingHome);
        } catch (Exception e) {
            log.error("养老院新增失败~");
            throw new RuntimeException(e);
        }
        //将新增的NursingHome的主键返回拿到
        Integer nursingHomeId = nursingHome.getId();
        //查询用户端user
        User user = userMapper.getById(application.getUserId());
        //调用方法判断用户提供的身份证是男/女
        Integer gender = genderFromIDCard(application.getIdCard());
        //调用方法判断用户提供的身份证今年几岁
        String age = calculateAgeFromIDCard(application.getIdCard());
        //将用户端user账号数据复制到adminUser
        AdminUser adminUser = AdminUser.builder()
                .nursingHomeId(nursingHomeId)
                .name(application.getDirector())
                .age(age)
                .gender(gender)
                .idCard(application.getIdCard())
                .headshot(user.getHeadshot())
                .phone(application.getPhone())
                .password(user.getPassword())
                .permissions(AdminUser.NURSING_HOME_MANAGEMENT)
                .position(AdminUser.DEAN)
                .status(AdminUser.ENABLED)
                .build();
        //创建账号
        try {
            adminUserMapper.addAdminUser(adminUser);
        } catch (Exception e) {
            log.error("账号创建失败~");
            throw new RuntimeException(e);
        }
        //将application的状态设置为1
        NursingHomeApplication build = NursingHomeApplication.builder()
                .id(applicationId)
                .status(NursingHomeApplication.APPROVED)
                .build();
        entryManagementMapper.passApplication(build);
    }

    public Integer genderFromIDCard(String idCard){
        // 检查身份证号码长度是否合法
        if (idCard.length() != 15 && idCard.length() != 18) {
            throw new DataNotExistException(MessageConstant.ILLEGAL_ID_CARD);
        }
        int genderDigit;
        // 对于 15 位身份证号码，第 15 位代表性别
        if (idCard.length() == 15) {
            genderDigit = Integer.parseInt(idCard.substring(14, 15));
        }
        // 对于 18 位身份证号码，第 17 位代表性别
        else {
            genderDigit = Integer.parseInt(idCard.substring(16, 17));
        }
        // 判断性别
        if (genderDigit % 2 == 1) {
            return 1;
        } else {
            return 0;
        }
    }

    public String calculateAgeFromIDCard(String idCard) {
        try {
            // 检查身份证号码长度是否合法
            if (idCard.length() != 15 && idCard.length() != 18) {
                throw new IllegalArgumentException("无效的身份证号码");
            }
            int birthYear, birthMonth, birthDay;
            // 对于 15 位身份证号码，年份需要补全
            if (idCard.length() == 15) {
                birthYear = 1900 + Integer.parseInt(idCard.substring(6, 8));
                birthMonth = Integer.parseInt(idCard.substring(8, 10));
                birthDay = Integer.parseInt(idCard.substring(10, 12));
            }
            // 对于 18 位身份证号码
            else {
                birthYear = Integer.parseInt(idCard.substring(6, 10));
                birthMonth = Integer.parseInt(idCard.substring(10, 12));
                birthDay = Integer.parseInt(idCard.substring(12, 14));
            }
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 构建出生日期
            LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
            // 计算年龄
            Period period = Period.between(birthDate, currentDate);

            return String.valueOf(period.getYears());
        } catch (Exception e) {
            // 捕获异常，默认年龄设置为 50
            return "50";
        }
    }
}
